const url_config = require('../../common/config');
var that;
var app = getApp();
var versionCompareRes = 1;
var getCategoriesSuccess = false;
Page({
  data: {
    'fileUrl': url_config.url_microFileService,
    userInfo: {
      head_img: '../../images/icon_user.png',
      nick_name: '——',
    },
    balance: 0.00,
    questioncount: 0,
    webTitle: '',
    webUrl: '',
    rankRule: '',
    actionNoticeShowTimes: 0,
    actionTitle: '',
    actionDesc: '',
    categories: [], //科目分类
    //分享排名
    rankList: [],
    uid_leader: '', //分享人的uid
    couldShare: false, //是否可以分享人气排名
  },
  onLoad: function(options) {
    that = this;
    let uid_leader = options.uid_leader;
    if (uid_leader) {
      that.setData({
        uid_leader: uid_leader
      })
    }
    getCategoriesSuccess = false;
    //获取微信基础库版本
    let systemInfo = wx.getSystemInfoSync();
    versionCompareRes = app.compareVersion('1.4.4', systemInfo.SDKVersion);
    if (versionCompareRes > 0) {
      //说明当前的微信sdk版本小于1.4.4
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，请升级到最新微信版本后重试。'
      })
      return;
    }
  },

  onShow: function() {
    if (!getCategoriesSuccess) {
      that.getAllCategories();
    }
    that.fetchUserInfo(true);
    //获取排名数据
    that.getRankingList();
  },
  fetchUserInfo: function(isCheck) {
    app.getUserinfoByCode(function(userInfo) {
      console.log(userInfo)
      userInfo.nick_name = userInfo.nick_name == '' ? '——' : userInfo.nick_name;
      userInfo.head_img = userInfo.head_img == '' ? '../../images/icon_user.png' : (userInfo.head_img.indexOf('http') == 0 ? userInfo.head_img : that.data.fileUrl + userInfo.head_img);
      that.setData({
        userInfo: userInfo
      });
      that.getUserQuestionCountandBalance();
      //人气排名数据上传
      that.updateRankingData();
      if (isCheck && userInfo.token && userInfo.nick_name.indexOf('——') == 0 || userInfo.head_img.indexOf('../../images/icon_user.png') == 0) {
        that.checkIsToLogin();
      } else {
        that.isUserHaveLogin();
      }
    });
  },

  //检测是否去登录（获取用户昵称头像等信息）
  checkIsToLogin: function() {
    if (!that.isUserHaveLogin()) {
      wx.showModal({
        title: '微信登录',
        content: '请先进行微信登录',
        success: function(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '../login/login',
            })
          }
        }
      });
    }
  },

  //检测用户是否已经登录
  isUserHaveLogin: function() {
    if (versionCompareRes <= 0 && (that.data.userInfo.nick_name.indexOf('——') == 0 || that.data.userInfo.head_img.indexOf('../../images/icon_user.png') == 0)) {
      that.setData({
        couldShare: false
      })
      console.log('false');
      return false;
    } else {
      that.setData({
        couldShare: true
      })
      console.log('true');
      return true;
    }
  },

  //获取所有的科目信息
  getAllCategories: function() {
    wx.request({
      url: url_config.url_getAllCategories,
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      success: function(res) {
        getCategoriesSuccess = true;
        let resJson = res.data;
        that.setData({
          categories: resJson.data
        })
      },
      fail: function() {
        wx.showModal({
          title: '提示',
          content: '获取科目数据失败，请检查网络是否畅通',
          confirmText: '再试一次',
          success: function(res) {
            if (res.confirm) {
              that.getAllCategories();
            }
          }
        })
      }
    })
  },

  getUserQuestionCountandBalance: function() {
    wx.request({
      url: url_config.url_getUserQuestionCountandBalance,
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'uidusernamekey': app.globalData.userInfo.token
      },
      success: function(res) {
        let resData = res.data.data;
        that.setData({
          balance: resData.balance,
          questioncount: resData.questioncount,
          webUrl: resData.webUrl,
          webTitle: resData.webTitle,
          rankRule: resData.rankRule,
          actionTitle: resData.actionTitle,
          actionDesc: resData.actionDesc,
          actionNoticeShowTimes: ++that.data.actionNoticeShowTimes
        })

      },
      fail: function() {
        wx.showModal({
          title: '提示',
          content: '获取用户余额数据失败，请检查网络是否畅通',
          confirmText: '再试一次',
          success: function(res) {
            if (res.confirm) {
              that.getUserQuestionCountandBalance();
            }
          }
        })
      }
    })
  },

  //更新人气排名
  updateRankingData: function() {
    if (!that.data.uid_leader) {
      return;
    }
    wx.request({
      url: url_config.url_update_user_ranking,
      data: {
        'uid_leader': that.data.uid_leader,
        'uid_member': that.data.userInfo.uid
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'uidusernamekey': app.globalData.userInfo.token
      }
    })
  },

  //获取排名数据
  getRankingList: function() {
    wx.request({
      url: url_config.url_get_ranking_list,
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'uidusernamekey': app.globalData.userInfo.token
      },
      success: function(res) {
        let resData = res.data.data;
        if (resData && resData.length > 0) {
          that.setData({
            rankList: resData
          })
        }
      },
      fail: function() {

      }
    })
  },

  // 跳转提问历史页面
  showQHistory: function() {
    if (that.data.userInfo.questionCount <= 0) {
      wx.showModal({
        title: '提示',
        content: '您还没有提问历史，快去选择科目提问吧！',
        confirmText: '朕知道了',
        success(res) {
          if (res.confirm) {

          }
        }

      })
      return;
    }
    wx.navigateTo({
      url: '../qhistory/qhistory',
    })
  },
  //余额条目点击
  onBalanceClick: function() {
    wx.showModal({
      title: '提示',
      content: '余额在线充值功能暂未开通，如需充值请咨询17600512681（微信同号）',
    })
  },
  //头部条目点击
  onHeaderItemClick: function(e) {
    console.log(e);
    that.parseFormId(e);
  },
  // 条目点击
  onSubjectItemClick: function(e) {
    that.parseFormId(e);
    if (that.data.userInfo.balance < 2) {
      wx.showModal({
        title: '提示',
        content: '您的余额不足2元，余额在线充值功能暂未开通，如需充值请咨询17600512681（微信同号）',
      })
      return;
    }
    if (!that.isUserHaveLogin()) {
      wx.navigateTo({
        url: '../login/login',
      })
      return;
    }
    let topName = e.target.dataset.topname;
    let item = e.target.dataset.item;
    wx.navigateTo({
      url: '../askQuestion/askQuestion?topName=' + topName + '&secondName=' + item.cname + '&cid=' + item.cid + '&fromType=microWx',
    })
  },
  parseFormId: function(e) {
    if (e && e.detail && e.detail.formId) {
      //将formid添加到app globalData中
      let formid = e.detail.formId;
      app.uploadFormId(formid);
    }
  },
  //排名分享按钮的点击事件
  toLogin: function() {
    wx.navigateTo({
      url: '../login/login',
    })
  },
  //跳转关注公众号界面
  focusGongzhong: function() {
    wx.navigateTo({
      url: '../web/web?url=' + that.data.webUrl,
    })
  },
  //关闭公告栏
  closeNotice: function() {
    that.setData({
      actionNoticeShowTimes: 0
    })
  },
  // 分享
  onShareAppMessage: function() {
    // let coverImg = that.data.fileUrl + that.data.userInfo.share_imgcover;
    let uid_leader = that.data.userInfo.uid;
    let head_img = that.data.userInfo.head_img;
    let nick_name = that.data.userInfo.nick_name;
    console.log(nick_name)
    return {
      title: nick_name + '邀请您参加人气大比拼，分享就能赚钱，比抢红包还过瘾！',
      imageUrl: head_img,
      path: '/pages/index/index?uid_leader=' + uid_leader,
    }
  },

});